package net.pm.core.aspect;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.pm.common.toolkit.DevConstant;
import net.pm.common.toolkit.PMTool;
import net.pm.common.toolkit.ReflectionUtils;
import net.pm.core.annotation.PowerCode;
import net.pm.core.entities.db.Pmuser;
import net.pm.core.web.BaseController;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限过滤
 */
@Aspect
@Component
public class PM_05_PowerAspect {

	/**
	 * 权限检查
	 * 
	 * @return
	 * @throws Throwable
	 */
	@SuppressWarnings("unchecked")
	@Around(value = "@annotation(net.pm.core.annotation.PowerCode)")
	public Object powerCheck(ProceedingJoinPoint joinPoint) throws Throwable {
		final BaseController controller = (BaseController) joinPoint
				.getTarget();
		final HttpSession session = controller.obtainSession();
		
		//获取当前的用户
		Pmuser ownerUser = (Pmuser) session.getAttribute(DevConstant.SESSION_CURRENT_USER);
		if(ownerUser.getIsAdmin()){//如果是管理员,放过
			return joinPoint.proceed();
		}
		
		// 拿当前用户的权限
		List<String> ownerUserPower = (List<String>) session
				.getAttribute(DevConstant.SESSION_CURRENT_USER_POWER);
		// 拿到当前用户所在的部门的权限
		List<String> ownerDeptPower = (List<String>) session
				.getAttribute(DevConstant.SESSION_CURRENT_DEPT_POWER);

		// 拿到目标方法
		final Method method = ReflectionUtils.obtainMethod(controller,
				joinPoint.getSignature().getName());

		PowerCode powercode;
		if ((powercode = method.getAnnotation(PowerCode.class)) != null) {
			String code = powercode.code().toString();
			System.out.println(code.toString());
			if (!PMTool.isHasPower(code, ownerUserPower)) {// 当前用户没有该权限
				if (!PMTool.isHasPower(code, ownerDeptPower)) {// 当前用户所在的部门也没有该权限

					if (method.getReturnType() == String.class)
						return "redirect:/error/nonpower.htm";
					else if (method.getReturnType() == ModelAndView.class)
						return new ModelAndView("redirect:/error/nonpower.htm");
					else
						return null;
					
				}
			}
		}

		// 最终放过
		return joinPoint.proceed();

	}



}
